package org.tp8.sampleapp.view.validator;

import java.util.LinkedList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.tp8.sampleapp.exc.SampleAppException;
import org.tp8.sampleapp.rule.intf.RuleService;
import org.tp8.sampleapp.rule.model.RuleModelWrapper;

/**
 * The Class NotEmptyValidator.
 */
@Component("notEmptyValidator")
@FacesValidator("notEmptyValidator")
public class NotEmptyValidator implements Validator {

	/** The app context. */
	@Autowired
	private RuleService ruleService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.validator.Validator#validate(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		FacesMessage msg;
		RuleModelWrapper ruleModelWrapper;
		try {
			ruleModelWrapper = ruleService.execute("kbCommonNotEmpty", value);
		} catch (SampleAppException e) {
			msg = new FacesMessage(e.getMessage());
			msg.setSeverity(FacesMessage.SEVERITY_FATAL);
			throw new ValidatorException(msg);
		}

		List<String> errorCodes = ruleModelWrapper.getErrorCodes();
		List<FacesMessage> facesMessages = new LinkedList<FacesMessage>();
		if (!errorCodes.isEmpty()) {
			for (String errorCode : errorCodes) {
				msg = new FacesMessage(errorCode);
				msg.setSeverity(FacesMessage.SEVERITY_ERROR);
				facesMessages.add(msg);
			}
			throw new ValidatorException(facesMessages);
		}
	}

}
